import { Component, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { DataTableComponent, DialogService, TableWidthConfig } from 'ng-devui';
import { SharedMethodService } from 'src/app/@core/services/Sharedmethod/shared-method.service';
import { JobOrderService } from 'src/app/@core/services/jobOrder/job-order.service';
import { AssignUserComponent } from 'src/app/@shared/components/assign-user/assign-user.component';

@Component({
  selector: 'app-process-dispatch',
  templateUrl: './process-dispatch.component.html',
  styleUrls: ['./process-dispatch.component.scss']
})
export class ProcessDispatchComponent {
  msgs: Array<Object> = [];
  tableData: any[] = [
    {}
  ]
  options = [
    '已派工',
    '未派工',
  ]
  weiWaiOptions = [
    '委外',
    '未委外',
  ]
  dataTableOptions = {
    columns: [

      {
        field: '工单号',
        header: '工单号',
        fieldType: 'text',
      },

      {
        field: '工序序号',
        header: '工序序号',
        fieldType: 'text',
      },
      {
        field: '工序编码',
        header: '工序编码',
        fieldType: 'text',
      },
      {
        field: '工序名称',
        header: '工序名称',
        fieldType: 'text',
      },
      {
        field: '产品编码',
        header: '产品编码',
        fieldType: 'text',
      },
      {
        field: '产品名称',
        header: '产品名称',
        fieldType: 'text',
      },
      {
        field: '产品规格',
        header: '产品规格',
        fieldType: 'text',
      },
      {
        field: '操作工',
        header: '操作工',
        fieldType: 'text',
      },
      {
        field: '是否委外',
        header: '是否委外',
        fieldType: 'text',
      },
      {
        field: '状态',
        header: '状态',
        fieldType: 'text',
      },
      {
        field: '计划数',
        header: '计划数',
        fieldType: 'text',
      },

      {
        field: '完成进度',
        header: '完成进度',
        fieldType: 'text',
      },
      {
        field: '剩余数',
        header: '剩余数',
        fieldType: 'text',
      },

      {
        field: '计划开工时间',
        header: '计划开工时间',
        fieldType: 'text',
      },
      {
        field: '计划完工时间',
        header: '计划完工时间',
        fieldType: 'text',
      },
    ]
  }
  tableWidthConfig: TableWidthConfig[] = [
    {
      field: 'checkbox',
      width: '80px'
    },
    {
      field: '操作',
      width: '160px'
    },
    {
      field: '工单号',
      width: '140px'
    },
    {
      field: '工序序号',
      width: '160px'
    },

    {
      field: '工序编码',
      width: '150px'
    },
    {
      field: '工序名称',
      width: '100px'
    },
    {
      field: '规格型号',
      width: '100px'
    },
    {
      field: '是否委外',
      width: '100px'
    },
    {
      field: '工序序号',
      width: '100px'
    },
    {
      field: '工序',
      width: '180px'
    },
    {
      field: '操作工',
      width: '100px'
    },
    {
      field: '状态',
      width: '100px'
    },
    {
      field: '计划数',
      width: '100px'
    },
    {
      field: '完成进度',
      width: '150px'
    },
    {
      field: '剩余数',
      width: '100px'
    },

    {
      field: '计划开工时间',
      width: '100px'
    },
    {
      field: '计划完工时间',
      width: '100px'
    },
  ]
  checkedIds = []
  pager = {
    total: 20,
    pageIndex: 1,
    pageSize: 20
  }
  pageSizeOptions = [10, 20, 30, 50, 100];
  productJob = []
  PartNum: string = null;
  PartName: string = null;
  JobOrderNum: string = null;
  JobOrderStatus: string = null;
  ProcessNum: string = null;
  ProcessName: string = null;
  @ViewChild(DataTableComponent, { static: true }) datatable: DataTableComponent;
  isIconRotated = false;
  weiwai: string;
  constructor(private SharedMethodService: SharedMethodService, private JobOrderService: JobOrderService, private Router: Router, private DialogService: DialogService) { }
  ngOnInit(): void {
    this.JobOrderService.GetJobOrdersProcess2(this.PartNum, this.PartName, this.JobOrderNum, this.JobOrderStatus, this.ProcessNum, this.ProcessName, this.pager.pageIndex, this.pager.pageSize, this.weiwai,true).subscribe((data: any) => {
      this.tableData = data.items
      this.updateSelection()
      this.pager.total = data.totalCount
    })
  }
  pageIndexChange($event: any) {
    this.JobOrderService.GetJobOrdersProcess2(this.PartNum, this.PartName, this.JobOrderNum, this.JobOrderStatus, this.ProcessNum, this.ProcessName, this.pager.pageIndex, this.pager.pageSize, this.weiwai,true).subscribe((data: any) => {
      this.tableData = data.items
      this.updateSelection()
      this.pager.total = data.totalCount
    })
  }//切换页码
  pageSizeChange($event: any) {
    this.JobOrderService.GetJobOrdersProcess2(this.PartNum, this.PartName, this.JobOrderNum, this.JobOrderStatus, this.ProcessNum, this.ProcessName, this.pager.pageIndex, this.pager.pageSize, this.weiwai,true,).subscribe((data: any) => {
      this.tableData = data.items
      this.updateSelection()
      this.pager.total = data.totalCount
    })
  }//改变每页显示数量
  showToast(type: any, summary: any, content: any) {
    switch (type) {
      default:
        this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  }//提示框
  cleared() {
    this.SharedMethodService.cleared(this.checkedIds, this.tableData, this.datatable).subscribe((data: any) => {
      this.checkedIds = data.map((row: { [x: string]: any; $checked: any; $halfChecked: any; }) => {
        const { $checked, $halfChecked, ...rest } = row;
        return rest;
      });;
    })
  }
  onRowCheckChange(checked: any, rowIndex: any, nestedIndex: any, rowItem: { $checked: any; $halfChecked: boolean; id: any; }) {
    rowItem.$checked = checked;
    rowItem.$halfChecked = false;
    this.datatable.setRowCheckStatus({
      rowIndex: rowIndex,
      nestedIndex: nestedIndex,
      rowItem: rowItem,
      checked: checked
    });
    this.checkAllChange()
  }
  allCheckedStatus = false;
  checkAllChange() {
    const rows = this.datatable.getCheckedRows();
    this.checkedIds = rows
  }
  //获取选中行
  updateSelection() {
    for (let row of this.tableData) {
      if (this.checkedIds.some(id => id.jobOrderId === row.jobOrderId && id.processId === row.processId)) {
        row.$checked = true;
      }
    }
  }
  search() {
    this.JobOrderService.GetJobOrdersProcess2(this.PartNum, this.PartName, this.JobOrderNum, this.JobOrderStatus, this.ProcessNum, this.ProcessName, this.pager.pageIndex, this.pager.pageSize, this.weiwai,true).subscribe((data: any) => {
      this.tableData = data.items
      this.updateSelection()

      this.pager.total = data.totalCount
    })
  }
  reset() {
    this.PartNum = null;
    this.PartName = null;
    this.JobOrderNum = null;
    this.JobOrderStatus = null;
    this.ProcessNum = null;
    this.ProcessName = null;
    this.weiwai = null;
    this.JobOrderService.GetJobOrdersProcess2(this.PartNum, this.PartName, this.JobOrderNum, this.JobOrderStatus, this.ProcessNum, this.ProcessName, this.pager.pageIndex, this.pager.pageSize, this.weiwai,true).subscribe((data: any) => {
      this.tableData = data.items
      this.updateSelection()
      this.pager.total = data.totalCount
    })
  }
  getNames(rowItem: any): string {
    if (rowItem.users) {
      return rowItem.users.map((user: { name: any; }) => user.name).join('，');
    } else {
      return '';
    }
  }
  dispatch(rowItem?: any, dialogtype?: string,) {
    if (this.checkedIds.length > 0 && rowItem == null) {
      const employeeCodeArrays = this.checkedIds.map(item => item.users.map(user => user.employeeCode));
      const isDispatch = this.allArraysEqual(employeeCodeArrays);
      if (!isDispatch) {
        this.showToast('error', '错误', '请选择相同操作工的工序进行派工')
        return;
      }else{
        const results = this.DialogService.open({
          title: '分配人员',
          data: {
            data: this.checkedIds,
            title: '派工'
          },
          content: AssignUserComponent,
          dialogtype: dialogtype,
          width: '1000px',
          draggable:false,
          onClose: () => {
          },
          buttons: [
            {
              cssClass: 'stress',
              text: '确定',
              handler: ($event: Event) => {
                this.JobOrderService.GetJobOrdersProcess2(this.PartNum, this.PartName, this.JobOrderNum, this.JobOrderStatus, this.ProcessNum, this.ProcessName, this.pager.pageIndex, this.pager.pageSize,this.weiwai,true).subscribe((data: any) => {
                  this.tableData = data.items
                  this.pager.total = data.totalCount
                  this.checkedIds = []
                })
                results.modalInstance.hide();
              }
            },
            {
              id: 'btn-cancel',
              cssClass: 'common',
              text: '取消',
              handler: ($event: Event) => {
                results.modalInstance.hide();
              },
            },
          ],
        });
      }
    } else if (rowItem) {
      const results = this.DialogService.open({
        title: '分配人员',
        data: {
          data: [rowItem],
          title: '派工'
        },
        content: AssignUserComponent,
        dialogtype: dialogtype,
        width: '1000px',
        draggable:false,
        onClose: () => {
        },
        buttons: [
          {
            cssClass: 'stress',
            text: '确定',
            handler: ($event: Event) => {
              this.JobOrderService.GetJobOrdersProcess2(this.PartNum, this.PartName, this.JobOrderNum, this.JobOrderStatus, this.ProcessNum, this.ProcessName, this.pager.pageIndex, this.pager.pageSize,this.weiwai,true).subscribe((data: any) => {
                this.tableData = data.items
                this.pager.total = data.totalCount
                this.checkedIds = []
              })
              results.modalInstance.hide();
            }
          },
          {
            id: 'btn-cancel',
            cssClass: 'common',
            text: '取消',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          },
        ],
      });
    }
    else {
      this.showToast('error', '错误', '请选择要派工的工序')
    }
  }
  revokeAssign( rowItem:any,dialogtype?: string,) {
    const data  = [{
      jobOrderProcessID:rowItem.jobOrderProcessId
    }]
    const results = this.DialogService.open({
      title: '分配人员',
      data: {
        title: '撤回',
      },
      content: '是否全部撤回？',
      dialogtype: dialogtype,
      width: '400px',

      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
              this.JobOrderService.RevokeAssignProcessesToUser(data).subscribe((data: any) => {
                this.showToast('success', '成功', '撤回成功')
                this.JobOrderService.GetJobOrdersProcess2(this.PartNum, this.PartName, this.JobOrderNum, this.JobOrderStatus, this.ProcessNum, this.ProcessName, this.pager.pageIndex, this.pager.pageSize,this.weiwai,true).subscribe((data: any) => {
                  this.tableData = data.items
                  this.pager.total = data.totalCount
                })
              }, error => {
                this.showToast('error', '失败', error.error)
              })

            results.modalInstance.hide();
          }
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  allArraysEqual(arrays: string[][]): boolean {
    if (arrays.length < 2) return true;
    for (let i = 1; i < arrays.length; i++) {
        if (!this.arraysEqual(arrays[0], arrays[i])) {
            return false;
        }
    }
    return true;
}
arraysEqual(arr1: string[], arr2: string[]): boolean {
  if (arr1.length !== arr2.length) return false;
  const sortedArr1 = arr1.slice().sort();
  const sortedArr2 = arr2.slice().sort();
  return sortedArr1.every((value, index) => value === sortedArr2[index]);
}

  // ================= 打印（工序派发） =================
  printSelected(): void {
    if (!this.checkedIds || this.checkedIds.length !== 1) {
      this.showToast('warning', '提示', '请仅勾选一条工序进行打印');
      return;
    }
    const rowItem = this.checkedIds[0];
    const orderLike = {
      jobNum: rowItem.jobOrderNum,
      productNum: rowItem.productNum,
      productName: rowItem.productName,
      partType: rowItem.partType,
      jobOrderPlanStartDate: rowItem.planStartTime,
      jobOrderPlanEndDate: rowItem.planFinishTime,
    };
    const html = this.buildProcessListPrintHtml(orderLike, [rowItem]);
    this.printWithIframe(html);
  }

  private printWithIframe(html: string) {
    const iframe = document.createElement('iframe');
    iframe.style.position = 'fixed';
    iframe.style.right = '0';
    iframe.style.bottom = '0';
    iframe.style.width = '0';
    iframe.style.height = '0';
    iframe.style.border = '0';
    iframe.style.visibility = 'hidden';
    document.body.appendChild(iframe);

    const doc = iframe.contentDocument || iframe.contentWindow?.document as Document | undefined;
    if (!doc) { document.body.removeChild(iframe); return; }
    doc.open();
    doc.write(html);
    doc.close();

    setTimeout(() => {
      try { iframe.contentWindow?.focus(); iframe.contentWindow?.print(); }
      finally {
        setTimeout(() => { if (iframe && iframe.parentNode) iframe.parentNode.removeChild(iframe); }, 400);
      }
    }, 200);
  }

  private to2(n: any): string {
    const x = Number(n);
    if (isNaN(x)) return '';
    return x.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  }

  private fmtDateStr(input: any, withTime = false): string {
    if (!input) return '';
    const d = new Date(input);
    if (isNaN(d.getTime())) return String(input);
    const y = d.getFullYear();
    const m = String(d.getMonth() + 1).padStart(2, '0');
    const da = String(d.getDate()).padStart(2, '0');
    if (!withTime) return `${y}-${m}-${da}`;
    const hh = String(d.getHours()).padStart(2, '0');
    const mm = String(d.getMinutes()).padStart(2, '0');
    return `${y}-${m}-${da} ${hh}:${mm}`;
  }

  private buildProcessListPrintHtml(orderLike: any, processes: any[]): string {
    const to2 = this.to2.bind(this);
    const now = this.fmtDateStr(new Date(), true);
    const style = `
      <style>
        @page { size: A4; margin: 12mm; }
        * { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', 'PingFang SC', 'Microsoft YaHei', sans-serif; }
        .sheet { width: 210mm; min-height: 297mm; margin: 0 auto; }
        .header { display: grid; grid-template-columns: 1fr auto; align-items: center; }
        .title { font-size: 20px; font-weight: 700; }
        .meta { font-size: 12px; color: #555; }
        table { width: 100%; border-collapse: collapse; margin-top: 8px; }
        th, td { border: 1px solid #333; padding: 6px 8px; font-size: 12px; }
        th { background: #f5f7fa; }
        .sub-title { margin-top: 14px; font-weight: 700; font-size: 14px; }
        .process-block { margin-top: 8px; border: 1px solid #333; padding: 4px 6px; }
        .process-head { font-size: 12px; display: grid; grid-template-columns: repeat(4, 1fr); gap: 4px 8px; }
      </style>
    `;
    const safe = (v: any) => v ?? '';
    const title = '工序派发单';
    const headTable = `
      <table>
        <colgroup>
          <col style="width: 15%"/><col style="width: 35%"/>
          <col style="width: 15%"/><col style="width: 35%"/>
        </colgroup>
        <tbody>
          <tr><th>工单号</th><td>${safe(orderLike?.jobNum)}</td><th>产品编号</th><td>${safe(orderLike?.productNum)}</td></tr>
          <tr><th>产品名称</th><td>${safe(orderLike?.productName)}</td><th>规格型号</th><td>${safe(orderLike?.partType)}</td></tr>
          <tr><th>计划开始</th><td>${safe(this.fmtDateStr(orderLike?.jobOrderPlanStartDate, true))}</td><th>计划结束</th><td>${safe(this.fmtDateStr(orderLike?.jobOrderPlanEndDate, true))}</td></tr>
        </tbody>
      </table>
    `;
    const procBlocks = (processes || []).map((p: any) => {
      const userNames = Array.isArray(p?.users) ? p.users.map((u: any) => u?.name).filter(Boolean).join('、') : '';
      return `
        <div class="process-block">
          <div class="process-head">
            <div><b>工序序号：</b>${safe(p?.processNumber)}</div>
            <div><b>工序编码：</b>${safe(p?.processNum)}</div>
            <div><b>工序名称：</b>${safe(p?.processName)}</div>
            <div><b>操作工：</b>${userNames}</div>
            <div><b>计划产量：</b>${safe(p?.productionQuantity)}</div>
            <div><b>报工合格数：</b>${p?.qualifiedAmount != null ? to2(p?.qualifiedAmount) : ''}</div>
            <div><b>计划开工：</b>${safe(this.fmtDateStr(p?.planStartTime, true))}</div>
            <div><b>计划完工：</b>${safe(this.fmtDateStr(p?.planFinishTime, true))}</div>
          </div>
        </div>
      `;
    }).join('');

    const html = `
      <!doctype html>
      <html>
        <head>
          <meta charset="utf-8" />
          <title>${title}</title>
          ${style}
        </head>
        <body>
          <div class="sheet">
            <div class="header">
              <div class="title">${title}</div>
              <div class="meta">打印时间：${now}</div>
            </div>
            ${headTable}
            <div class="sub-title">工序信息</div>
            ${procBlocks || ''}
          </div>
        </body>
      </html>`;
    return html;
  }
}
